import { useQuery } from '@tanstack/react-query';
import React, { Dispatch, useEffect, useMemo, useState } from 'react';

import datasetService from '@/api/services/datasetService';
import { DatasetListItem, DatasetListReq } from '@/common/types/dataset/dataset';
import { t } from '@/locales/i18n';

import ParentPaths from '../common/ParentPaths';
import { CircleLoading } from '../loading';
import MyModal from '../MyModal';
import { WorkflowContext } from '@/pages/app/detail/components/Workflow/context';
import { useContextSelector } from 'use-context-selector';

type PathItemType = {
  parentId: string;
  parentName: string;
};

function DatasetSelectContainer({
  isOpen,
  setParentId,
  paths,
  onClose,
  tips,
  isLoading,
  children,
}: {
  isOpen: boolean;
  setParentId: Dispatch<string>;
  paths: PathItemType[];
  onClose: () => void;
  tips?: string | null;
  isLoading?: boolean;
  children: React.ReactNode;
}) {
  return (
    <MyModal
      iconSrc="/imgs/workflow/db.png"
      title={
        <div className="font-normal">
          <ParentPaths
            paths={paths.map((path, i) => ({
              parentId: path.parentId,
              parentName: path.parentName,
            }))}
            FirstPathDom={t('core.chat.Select dataset')}
            onClick={(e) => {
              setParentId(e);
            }}
          />
          {!!tips && <div className="text-sm font-normal text-gray-600">{tips}</div>}
        </div>
      }
      isOpen={isOpen}
      onClose={onClose}
      minW="600px"
      // h={'80vh'}
      // w={'100%'}
      // maxW={['90vw', '900px']}
      // isCentered
    >
      {isLoading ? <CircleLoading /> : <div className="h-full">{children}</div>}
    </MyModal>
  );
}

// 获取数据集
const getDatasets = (params: DatasetListReq): Promise<DatasetListItem[]> => {
  return datasetService.getDatasetList(params).list;
};

export function useDatasetSelect() {
  const [parentId, setParentId] = useState<string>('');
  const app_id = useContextSelector(WorkflowContext, (v) => v.appId);
  const { data, isFetching, refetch } = useQuery({
    queryKey: ['loadDatasetData', parentId],
    queryFn: () =>
      Promise.all([
        datasetService.getDatasetList({ parentId, app_id }),
        datasetService.getDatasetPaths(parentId),
      ]),
  });

  // const { data, isFetching } = useQuery(['loadDatasetData', parentId], () =>
  //   Promise.all([getDatasets({ parentId }), getDatasetPaths(parentId)])
  // );

  const paths = useMemo(() => [...(data?.[1] || [])], [data]);

  useEffect(() => {
    console.log('paths : ', paths);
    console.log('data : ', data);
    console.log('parentId : ', parentId);
  }, [paths, parentId, data]);

  return {
    parentId,
    setParentId,
    datasets: (data && data[0].list) || [],
    paths,
    isFetching,
    refetch,
  };
}

export default DatasetSelectContainer;
